package aa.jx.order.controller;


import aa.jx.order.model.Order;
import aa.jx.order.model.OrderItem;
import aa.jx.order.service.OrderService;
import aa.jx.register.model.Address;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Collections;
import java.util.List;

@RestController
@RequestMapping("/api/orders")
public class OrderController {
    @Autowired
    private OrderService orderService;

    @PostMapping
    public Order createOrder(@RequestParam Integer userId,
                             @RequestParam Integer addressId,
                             @RequestBody List<OrderItem> cartItems) {
        return orderService.createOrder(userId, addressId, cartItems);
    }

    @GetMapping("/{orderId}")
    public Order getOrderDetail(@PathVariable Long orderId) {
        Order order = orderService.getOrderDetail(orderId);
        // 确保地址不为null
        if (order.getAddress() == null) {
            order.setAddress(new Address()); // 设置空对象避免NPE
        }
        return order;
    }

    @GetMapping
    public List<Order> getUserOrders(@RequestParam Integer userId) {
        List<Order> orders = orderService.getUserOrders(userId);
        orders.forEach(order -> {
            if (order.getOrderItems() == null) order.setOrderItems(Collections.emptyList());
            if (order.getAddress() == null) order.setAddress(new Address()); // 或保持 null
        });
        return orders;
    }


}